import 'dart:convert';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:bxultimate/app/theme/gaps.dart';
import 'package:bxultimate/data/store/auth_store.dart';
import 'package:bxultimate/resources/assets.dart';
import 'package:bxultimate/shared/shared.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:pretty_qr_code/pretty_qr_code.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';

import 'controller.dart';

class OrganizationAccessRegQrcodePage extends StatefulWidget {
  const OrganizationAccessRegQrcodePage({Key? key}) : super(key: key);

  @override
  State<OrganizationAccessRegQrcodePage> createState() =>
      _OrganizationAccessRegQrcodePageState();
}

class _OrganizationAccessRegQrcodePageState
    extends State<OrganizationAccessRegQrcodePage> {
  final controller = Get.find<OrganizationAccessRegQrcodeController>();
  final state = Get.find<OrganizationAccessRegQrcodeController>().state;
  GlobalKey _repainKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
          color: Get.theme.scaffoldBackgroundColor,
          image: DecorationImage(
              image: AssetImage(Assets.organizationCheckQrCode),
              fit: BoxFit.cover,
              alignment: Alignment.topCenter)),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        appBar: TDNavBar(
          backgroundColor: Colors.transparent,
          title: '登记二维码',
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Obx(()=>Container(
                width: Get.width * 0.5,
                height: Get.width * 0.5,
                padding: EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(8),
                ),
                child: PrettyQrView.data(
                  data: 'https://sxmbxt.com/#/entrAndExitRegistration/checkpointId=${state.info.id}&userId=${AuthStore.to.profile.id}',
                ),
              )),
              Gaps.vGap12,
              Obx(() => Text(
                    '${state.info.name}',
                    style: TextStyle(color: Colors.white, fontSize: 20),
                  ))
            ],
          ),
        ),
      ),
    );
  }

  saveToMobile() async {
    bool hasPermission = await UtilPermission.requestStoragePermission();
    if (!hasPermission) {
      SmartDialog.showToast('请先授予存储权限');
      return;
    }
    SmartDialog.showLoading(msg: '生成中...');

    BuildContext? buildContext = _repainKey.currentContext;
    RenderRepaintBoundary? boundary =
        buildContext!.findRenderObject() as RenderRepaintBoundary?;
    ui.Image image = await boundary!.toImage();
    ByteData? _byteData =
        await image.toByteData(format: ui.ImageByteFormat.png);
    await ImageGallerySaver.saveImage(_byteData!.buffer.asUint8List(),
        quality: 300, name: '商家码');
    SmartDialog.dismiss();
    SmartDialog.showNotify(msg: '已保存至本地相册', notifyType: NotifyType.success);
  }

  @override
  void dispose() {
    Get.delete<OrganizationAccessRegQrcodeController>();
    super.dispose();
  }
}
